package jobs.job3.classloaderdemo.client;

import jobs.job3.classloaderdemo.server.standard.bean.TaskBean;
import jobs.job3.classloaderdemo.server.standard.Task;

import java.io.*;
import java.net.Socket;

public class CNClient<O> extends ClassLoader {
    String ip;
    int port;

    public CNClient(String ip, int port) throws IOException {
        this.ip = ip;
        this.port = port;
    }

//    将taskBean 传输给 计算节点 ，并 接收 计算节点执行完成后的返回结果
    public O submitAndExecute(TaskBean taskBean) throws Exception {
       try (Socket socket = new Socket(ip, port)) {
           byte[] bytes = taskBean.serialize();//网络io，需要传输字节，因此将对象序列化为字节。
           System.out.println("《计算任务》数据包大小为：" + (bytes.length + 4) + " 个字节");
           DataOutputStream out = new DataOutputStream(socket.getOutputStream());
//           传输的数据格式
           out.writeInt(bytes.length);
           out.write(bytes);
           out.flush();
           System.out.println("发送成功，等待服务器返回结果...");


           DataInputStream in = new DataInputStream(socket.getInputStream());
//           解析服务器返回的数据包
           int len = in.readInt();
           byte[] result = new byte[len];
           in.readFully(result);


           byte[] taskBytes = taskBean.getTaskBytes();
           Class<?> taskClass = defineClass(taskBean.getClassName(), taskBytes, 0, taskBytes.length);
           //noinspection unchecked
           return ((Task<?, O>) taskClass.getConstructor().newInstance()).getSerializer().outputDeserialize(result);
       }
    }

}


